package com.master.service;

import com.master.dao.OrderDao;
import com.master.domain.MiaoshaOrder;
import com.master.domain.MiaoshaUser;
import com.master.domain.OrderInfo;
import com.master.redis.OrderKey;
import com.master.redis.RedisServer;
import com.master.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class OrderService {

    @Autowired
    OrderDao orderDao;

    @Autowired
    RedisServer redisServer;


    //获取用户的秒杀订单
    //判断用户是否已经秒杀过此商品
    //在判断用户是是否已经秒杀过商品,不去查询数据库,而去查询缓存
    public MiaoshaOrder getMiaoshaOrderByUserIdGoodsId(long userId, long goodsId) {
//        return orderDao.getMiaoshaOrderByUserIdGoodsId(userId,goodsId);
        return redisServer.get(OrderKey.getMiaoshaOrderByUidGid,""+userId+"_"+goodsId,MiaoshaOrder.class);
    }


    //创建订单OrderInfo
    //并创建秒杀订单MiaoshaOrder
    //将秒杀订单缓存在redis中
    @Transactional
    public OrderInfo createOrder(MiaoshaUser user, GoodsVo goodsVo) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setDeliveryAddrId(0L);
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsId(goodsVo.getId());
        orderInfo.setGoodsName(goodsVo.getGoodsName());
        orderInfo.setGoodsPrice(goodsVo.getMiaoshaPrice());
        orderInfo.setOrderChannel(1);
        orderInfo.setUserId(user.getId());
        orderInfo.setStatus(0);//0表示未支付

        orderDao.insert(orderInfo);//向数据库中插入一条订单数据

        MiaoshaOrder miaoshaOrder = new MiaoshaOrder();
        miaoshaOrder.setGoodsId(goodsVo.getId());
        miaoshaOrder.setOrderId(orderInfo.getId());
        miaoshaOrder.setUserId(user.getId());
        orderDao.insertMiaoshaOrder(miaoshaOrder);//向数据库中插入一条秒杀订单(MiaoshaOrder)数据

        //将秒杀订单MiaoshaOrder放入缓存redis中
        redisServer.set(OrderKey.getMiaoshaOrderByUidGid,""+user.getId()+"_"+goodsVo.getId(),MiaoshaOrder.class);
        return orderInfo;
    }


    public OrderInfo getOrderById(long orderId){
        return orderDao.getOrderById(orderId);
    }
}
